package pdf.itext7;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.extgstate.PdfExtGState;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;

import java.io.IOException;

public class PdfUtil {

    /**
     * 创建水印
     *
     * @param path          源文件路径
     * @param savePath      新文件路径
     * @param watermarkText 水印内容
     * @throws IOException
     */
    public static void createWatermark(String path, String savePath, String watermarkText) throws IOException {
        PdfDocument pdfDoc = null;
        try {
            final PdfFont font = PdfFontFactory.createFont("simfang.ttf", PdfEncodings.IDENTITY_H, false); //使用宋体作为水印的字体
            pdfDoc = new PdfDocument(new PdfReader(path), new PdfWriter(savePath));
            pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, event -> {
                PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
                PdfDocument pdfDoc1 = docEvent.getDocument();
                PdfPage page = docEvent.getPage();

                PdfCanvas canvas = new PdfCanvas(page);
                PdfExtGState gs1 = new PdfExtGState();
                gs1.setFillOpacity(0.5f); // 水印透明度
                canvas.setExtGState(gs1);
                new Canvas(canvas, page.getPageSize())
                        .setFontColor(ColorConstants.LIGHT_GRAY)
                        .setFontSize(60)
                        .setFont(font)
                        .showTextAligned(new Paragraph(watermarkText), 298, 421, pdfDoc1.getPageNumber(page), TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
            });
        } catch (IOException e) {
            throw e;
        } finally {
            if(pdfDoc != null){
                pdfDoc.close();
            }
        }
    }

}
